package org.ssm.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.ssm.pojo.User;
import org.ssm.pojo.UserFind;
import org.ssm.service.IUserService;

import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @RequestMapping("/list")
    public String findAll(Model model){
        List<User> userList = userService.findAll();;
        model.addAttribute("userList" , userList);
        return "list";
    }
    @RequestMapping("/form")
    public String form(){
        return "insert";
    }
    @RequestMapping("/updateForm/{id}")
    public String updateForm(Model model ,@PathVariable("id") Integer id){
        User user = userService.findOne(id);
        model.addAttribute("user" , user);
        return "update";
    }
    @RequestMapping("/insert")
    public String insert(User user){
        userService.insertUser(user);
        return "redirect:/user/pageList";
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id){
        userService.deleteUser(id);
        return "redirect:/user/pageList";
    }
    @RequestMapping("/update")
    public String update(User user){
        userService.updateUser(user);
        System.out.println(user);
        return "redirect:/user/pageList";
    }
    @RequestMapping("/pageList")
    public String pageList(Integer pageNum , Integer pageSize , Model model){
        if(pageNum==null || pageNum == 0){
            pageNum = 1;
        }
        if(pageSize==null || pageSize == 0){
            pageSize = 3;
        }
        PageHelper.startPage(pageNum , pageSize);
        List<User> users = userService.findAll();
        PageInfo<User> userPageInfo = new PageInfo<>(users);
        model.addAttribute("userList" , users);
        model.addAttribute("userPageInfo" , userPageInfo);
        return "/list";
    }
    @RequestMapping("/findSome")
    public String findSome(Model model , UserFind userFind){
        List<User> users = userService.findBySome(userFind);
        model.addAttribute("userList" , users);
        return "/list";
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }
}
